<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Hash;
use Mail;

class ZhuceController extends Controller
{
    // 注册页面
    public function getIndex(){
        return view('home/zhuce/index');
    }
    // // 用户注册
    public function postInsert(Request $request){
       
      // 验证用户是否存在
      $this->validate($request,[
            'password'=>'required',
            'repassword' => 'required|same:password',
      
    ],[

            'password.required'=>'请输入密码',
            'repassword.required' => '确认密码不存在',
            'repassword.same' => '确认密码不一致',
    ]);
    
       if($request -> only('email')){
        $y = DB::table('user') ->where('email',$request->only('email')) -> first();
        if(!empty($y)){
            return back() -> with('error','此用户存在');
        }
       } 
       // 验证验证码
    if(session('code') != $request->input('code')){
      return back() -> withInput()->with('error','验证码错误');
    }
       $s = $request -> only(['email','password','repassword']);
       // 验证密码
     if($s['password'] != $s['repassword']){
            return back()->with('error','俩次密码不一致');
     }
     $arr['email'] = $s['email'];
     $arr['password'] = Hash::make($s['password']);
     $arr['createtime'] = date('Y-m-d H:i:s',time());
     $arr['token'] = str_random(50);
    $arr['username'] = md5(time().rand(100000,999999));
   
  

     $id = DB::table('user')->insertGetId($arr);
   
     // 
    if($id > 0){
        // 发送邮箱$arr['email']  id $id token $arr['token']
        self::mailto($arr['email'],$id,$arr['token']); 
        return view('home/login/index',['id'=>$id]);

}
  
    }
    // 邮箱发送
    static public function mailto($email,$id,$token){
         Mail::send('home.email.index', ['id' => $id,'token'=>$token], function ($m) use ($email) {
          $m->to($email)->subject('注册邮件！!');
        });
    }
  
// 邮箱激活
    public function getJihuo(Request $request){
        $s = $request -> only('id','token');
        // 2 为激活
        $arr['disable'] = 2;
        $res = DB::table('user')->where('id',$s['id'])->where('token',$s['token'])->update($arr);
        if($res){
            // echo '激活成功';
            return redirect('/home/login/index?id='.$s['id'])->with('success','激活成功');
        }else{
            return back() -> with('error','激活失败');
        }
      
    }
    // 手机注册
    public function getShouji(){
       return view('home/zhucee/index');
    }
    
    //请求数据到短信接口，检查环境是否 开启 curl init。
    static public function Post($curlPost,$url){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_NOBODY, true);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
            $return_str = curl_exec($curl);
            curl_close($curl);
            return $return_str;
    }

    //将 xml数据转换为数组格式。
    static public function xml_to_array($xml){
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = self::xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

  
    

    public function postPhone(){
        //短信接口地址
        $target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
        //获取手机号
        $mobile = $_POST['mobile'];
        
        //生成的随机数
        $mobile_code = session(['phone_code'=>rand(1000,9999)]);
        $mobile_code = session('phone_code');
        if(empty($mobile)){
            exit('手机号码不能为空');
        }
        

        $post_data = "account=C07943574&password=77139c71ab8d7b7c5a5dd166dbfb7fc3&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");
        //用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
        //查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
        $gets =  self::xml_to_array(self::Post($post_data, $target));
        
        echo $gets['SubmitResult']['msg'];
    }

    public function postInsert2(Request $request){
        //var_dump(session('phone_code'));
        //dd($request->all());
        // array:3 [▼
        //   "_token" => "R7bXieWvpX1sAWvWJToChBURzYe1P7ESw4f7wBvU"
        //   "phone" => "17310933361"
        //   "code" => "7166"
        // ]
        if(session('phone_code') !=  $request ->input('code')){
            return back() -> withInput() -> with('error','验证码错误');

        }

         $s = $request -> only(['phone','password','repassword']);
         //var_dump($s);
         // 验证密码
         if($s['password'] != $s['repassword']){
                return back()->with('error','俩次密码不一致');
         }
         
         $arr['password'] = Hash::make($s['password']);
         $arr['createtime'] = date('Y-m-d H:i:s',time());
         $arr['token'] = str_random(50);
         $arr['username'] = md5(time().rand(100000,999999));
         $arr['tel'] = $request -> input('phone');
         $arr['disable'] = 2;
         // var_dump($arr);
       
      

        $id = DB::table('user')->insert($arr);
        //dd($id);
        
        if($id){
            
            return view('home/login/index',['id'=>$id]);
        }else{
          return back() -> withInput() -> with('error','注册失败');
        }

    }

}
